package models

import (
	"app-box/config"
	"encoding/json"
	"errors"
	"fmt"

	"github.com/speps/go-hashids"
)

type IDType int64

func NewID(idString string) (id IDType, err error) {
	hd := hashids.NewData()
	hd.Salt = config.Server.IdSalt
	hd.MinLength = 30
	h, err := hashids.NewWithData(hd)
	if err != nil {
		return
	}
	numbers, err := h.DecodeInt64WithError(idString)
	if err != nil {
		return
	}
	if len(numbers) < 1 {
		err = errors.New("Invalid ID")
		return
	}
	id = IDType(numbers[0])
	return
}

func (id IDType) MarshalJSON() ([]byte, error) {
	str, err := id.ToString()
	if err != nil {
		return []byte{}, err
	}
	return []byte(fmt.Sprintf("\"%s\"", str)), nil
}

func (id *IDType) UnmarshalJSON(b []byte) error {
	var jsonStr string
	if err := json.Unmarshal(b, &jsonStr); err != nil {
		return err
	}
	idValue, err := NewID(jsonStr)
	if err != nil {
		return err
	}
	*id = idValue
	return nil
}

func (id IDType) ToString() (string, error) {
	hd := hashids.NewData()
	hd.Salt = config.Server.IdSalt
	hd.MinLength = 30
	h, err := hashids.NewWithData(hd)
	if err != nil {
		return "", err
	}
	idStr, err := h.EncodeInt64([]int64{int64(id)})
	if err != nil {
		return "", err
	}
	return idStr, err
}

func (id IDType) ToIntString() string {
	return fmt.Sprintf("%d", id)
}
